<template>
    <div>
        <!--  顶部面包屑  -->
        <div class="ccui-navigation">
            <!-- 面包屑 -->
            <breadcrumb
                :breadcrumbArr="breadcrumbArr"
                :breadcrumbLastItem="breadcrumbLastItem"
                :state="$route.query.id ? 'edit' : 'create'"
                @handleBack="handleBack"
            />
        </div>
        <div v-if="isTrue" class="ccui-app-container-detail">
            <div class="ccui-app-container-detail-body">
                <el-tabs v-model="activeName" class="el-tabs__customize">
                    <el-tab-pane label="基本信息" name="a">
                        <basicInfo ref="basicInfo" :settlementForm="settlementForm" :editContractId="editContractId"/>
                    </el-tab-pane>
                    
                    <el-tab-pane label="结算单明细" name="b">
                        <tableList ref="tableList" :settlementForm="settlementForm" @childTableData="childTableData"/>
                    </el-tab-pane>
                    
                    <el-tab-pane label="验收单明细" name="c">
                        <purchaseList
                            ref="purchaseList"
                            :settlementList="settlementList"
                        />
                    </el-tab-pane>
                    
                    <el-tab-pane label="附件" name="d">
                        <fileInfo
                            ref="fileInfo"
                            v-model="fileList"
                            :state="$route.query.id?'edit' : 'create'"
                            v-if="isTrue"
                        ></fileInfo>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
        <!--  按钮  -->
        <el-bottom-guide>
            <ul class="ccui-bottom-button">
                <li>
                    <el-button
                        type="bottom"
                        icon="icon-ccui-save"
                        @click="submitKeep"
                    >暂存
                    </el-button>
                </li>
                <li>
                    <el-button
                        type="bottom"
                        icon="icon-ccui-save"
                        @click="submitHandle('save')"
                    >保存并校验
                    </el-button>
                </li>
                <li>
                    <el-button
                        type="bottom"
                        icon="icon-ccui-save"
                        @click="submitHandle('submit')"
                    >保存并提交
                    </el-button>
                </li>
                <div class="ccui-bottom-guide-divider"/>
                <li>
                    <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
                    >返回
                    </el-button>
                </li>
            </ul>
        </el-bottom-guide>
    </div>
</template>

<script>
import breadcrumb from "@/basa/components/public/breadcrumb";
import basicInfo from "@/app/settlement-management/equipment/eq_maintain/components/basicInfo";
import tableList from "@/app/settlement-management/equipment/eq_maintain/components/tableList";
import fileInfo from "@/basa/components/public/uploadInfo3";
import purchaseList from "@/app/settlement-management/equipment/eq_maintain/components/purchaseList";
import {saveSettlement, submitSettlement, editSettlement, tsSettlement, tempEdit, getById} from "@/app/settlement-management/equipment/api";
import {dateFormat1} from "@/basa/utils";

export default {
    name: "item_add",
    components: {breadcrumb, basicInfo, tableList, fileInfo, purchaseList},
    data() {
        return {
            settlementForm: {
                reportInOrgName: "",
                reportInOrgId: null,
                contractCode: "",
                contractName: "",
                settlementStart: "",
                settlementEnd: "",
                reportTime: dateFormat1(new Date()),
                settlementName: "",
                contractId: null,
                contractMoney: "",
                supplierId: null,
                supplierCode: "",
                supplierName: "",
                reportUsername: "",
                remarks: "",
                currSetCount: "",
                currSetMoney: "",
                billSource: "20",
                smpConcMatLessListBOS: [],
                smpPcConcBO: {},
            },
            isTrue: false,
            settlementList: [],
            activeName: "a",
            breadcrumbLastItem: "",
            // 面包屑导航
            breadcrumbArr: [
                {
                    path: "/settlement-management/settlement-maintenance-approval/settlement-maintenance-all",
                    text: "结算管理"
                },
                {
                    path: "/settlement-management/equipment-preserve/ListAll",
                    text: "设备采购结算管理"
                },
                {
                    path: "/settlement-management/equipment-preserve/ListAll",
                    text: "结算单维护"
                }
            ],
            fileList: [],
            editContractId: null
        }
    },
    methods: {
        saveSettlement,
        editSettlement,
        tsSettlement,
        tempEdit,
        // 保存 提交
        submitHandle(operType) {
            if (
                !this.settlementForm.settlementStart ||
                !this.settlementForm.settlementEnd ||
                this.settlementForm.settlementName == "" ||
                this.settlementForm.settlementName == undefined ||
                this.settlementForm.contractCode == "" ||
                this.settlementForm.supplierName == ""
            
            ) {
                this.activeName = "a";
                this.$message({
                    type: "error",
                    message: "请输入必填项",
                    ccuiCustom: true,
                    duration: 1500
                });
                this.$refs["basicInfo"].handleSubmit();
                this.activeName = "a";
                return;
            }
            
            let settlementCountBool = this.settlementList
                .filter(e => e.isOtherCost == 0 && !e.isCategories)
                .every(item => item.settlementCount != 0 && item.settlementCount != "");
            if (!settlementCountBool) {
                this.activeName = "b";
                this.$message.warning("结算数量不能为空/0");
                this.activeName = "b";
                return;
            }
            
            let isOtherCostZero = this.settlementList
                .filter(e => e.isOtherCost != 1 && !e.isCategories)
                .every(
                    item => item.unitPriceWithTax != "" && item.unitPriceWithTax != 0
                );
            if (!isOtherCostZero) {
                this.activeName = "b";
                this.$message.warning("单价不能为空/0");
                this.activeName = "b";
                return;
            }
            
            // 运输类 || e.isCategories  去除判断
            let isOtherCostOne = this.settlementList
                .filter(e => e.isOtherCost == 1)
                .every(
                    item =>
                        item.moneyWithTax &&
                        item.moneyWithTax != "" &&
                        item.moneyWithTax != 0 &&
                        item.taxRatePercent &&
                        item.taxRatePercent != ""
                );
            if (!isOtherCostOne) {
                this.activeName = "b";
                this.$message.warning(
                    "贴息/价格追涨/价格追跌/其他/运输类,税率/含税金额不能为空/0"
                );
                this.activeName = "b";
                return;
            }
            this.settlementList = this.handleSettlementList(this.settlementList);
            
            this.handleSaveData(operType);
        },
        handleBack() {
            this.$router.push("/settlement-management/equipment-preserve/ListAll");
        },
        handleSaveData(operType) {
            // 51 gistUploadIds 52 otherUploadIds
            this.$refs["basicInfo"].handleSubmit().then(form => {
                if (!this.$route.query.id) {
                    form.materialSource = form.smpPcConcBO.materialSource;
                }
                if (operType === "save") {
                    // 区分新增 or 编辑 this.$router.query.id
                    this.$route.query.id? this.handleSaveOrEditSettlement(form, this.editSettlement) : this.handleSaveOrEditSettlement(form, this.saveSettlement);
                } else if (operType === "submit") {
                    submitSettlement({
                        settlement: form,
                        settlementList: this.settlementList,
                        gistUploadIds: this.handleFilesParams().gistUploadIds,
                        otherUploadIds: this.handleFilesParams().otherUploadIds,
                        isShowPageLoading: true
                    }).then(res => {
                        if (res.data.code == "0") {
                            this.$message({
                                type: "success",
                                message: res.data.message
                            });
                            this.handleBack();
                        }
                    });
                }
            }).catch(e => {
                console.log('catch', e);
            });
        },
        // 暂存
        submitKeep() {
            this.$route.query.id? this.handleKeep(this.tempEdit) : this.handleKeep(this.tsSettlement);
        },
        handleKeep(callBack) {
            this.settlementList = this.handleSettlementList(this.settlementList);
            let params = {
                settlement: this.$refs["basicInfo"].settlementForm,
                settlementList: this.settlementList,
                gistUploadIds: this.handleFilesParams().gistUploadIds,
                otherUploadIds: this.handleFilesParams().otherUploadIds,
                isShowPageLoading: true
            };
            callBack(params).then(res => {
                this.$message({
                    type: "success",
                    message: res.data.message
                });
                this.handleBack();
            });
        },
        // 保存
        handleSaveOrEditSettlement(form, callBack) {
            callBack({
                settlement: form,
                settlementList: this.settlementList,
                gistUploadIds: this.handleFilesParams().gistUploadIds,
                otherUploadIds: this.handleFilesParams().otherUploadIds,
                isShowPageLoading: true
            }).then(res => {
                if (res.data.code == "0") {
                    this.$message({
                        type: "success",
                        message: res.data.message
                    });
                    this.handleBack();
                }
            });
        },
        // 处理settlementList入参
        handleSettlementList(data) {
            if (data.length) {
                let yunshu = [], // 运输类
                    hebingqian = [], // 没有合并的数据
                    hebinghou = [], // 合并后隐藏的数据
                    hebingMerge = [], // 合并后生成的数据
                    qita = []; // 其他类数据
                data.map(e => {
                    if (e.isCategories && e.isCategories == 1) {
                        yunshu.push(e);
                    } else if (e.isMerge == 0 && e.isMainInventory == 0 && e.isOtherCost == 0) {
                        hebingqian.push(e);
                    } else if (e.isMerge == 1 && e.isMainInventory == 0 && e.isOtherCost == 0) {
                        hebinghou.push(e);
                    } else if (e.isMerge == 1 && e.isMainInventory == 1 && e.isOtherCost == 0) {
                        hebingMerge.push(e);
                    } else if (e.isOtherCost && e.isOtherCost == 1) {
                        qita.push(e);
                    }
                });
                data = [...hebingqian, ...hebingMerge, ...yunshu, ...qita, ...hebinghou];
                
                data.forEach((item, index) => {
                    item.sn = index;
                    if (item.acceptanceCode != undefined) {
                        item.acceptCode = item.acceptanceCode;
                    }
                });
            } else {
                data = [];
            }
            return data;
        },
        // 处理附件入参
        handleFilesParams() {
            let gistUploadIds = [],
                otherUploadIds = [];
            
            this.fileList.map((e, i) => {
                if (e.fileType == 51) {
                    gistUploadIds.push({
                        fileDesc: e.fileDesc,
                        sn: i,
                        uploadId: e.uploadId,
                        uploadTime: e.createTime || e.uploadTime
                    });
                } else {
                    otherUploadIds.push({
                        fileDesc: e.fileDesc,
                        sn: i,
                        uploadId: e.uploadId,
                        uploadTime: e.createTime || e.uploadTime
                    });
                }
            });
            return {
                gistUploadIds: gistUploadIds,
                otherUploadIds: otherUploadIds
            };
        },
        childTableData(val) {
            this.settlementList = val;
        },
        // sort 排序
        handleSort(property) {
            return function (a, b) {
                return a[property] - b[property];
            }
        },
        getDetail() {
            getById({id: this.$route.query.id, isShowPageLoading: true}).then(res => {
                let result = res.data.data;
                this.settlementForm = result.settlement;
                this.editContractId = this.settlementForm.contractId;
                console.log(this.editContractId, 'this.editContractId');
                result.gistFiles.map(e => {
                    e.fileType = 51;
                    e.fileTypeName = "结算依据";
                });
                result.otherFiles.map(e => {
                    e.fileType = 52;
                    e.fileTypeName = "其他";
                });
                this.fileList = [...result.gistFiles, ...result.otherFiles];
                this.fileList.sort(this.handleSort('sn'));
                this.isTrue = true;
                result.settlementList.forEach(row => {
                    if (
                        row.categoryCode &&
                        (row.categoryCode.substr(0, 4) == "1305" ||
                            row.categoryCode.substr(0, 4) == "1306" ||
                            row.categoryCode.substr(0, 4) == "1307" ||
                            row.categoryCode.substr(0, 4) == "1308" ||
                            row.categoryCode.substr(0, 4) == "1309" ||
                            row.categoryCode.substr(0, 6) == "990103")
                    ) {
                        this.$set(row, "isCategories", 1);
                        this.$set(row, "settlementCount", row.unStorageCount?(+row.unStorageCount).toFixed(3): "");
                    } else {
                        this.$set(row, "settlementCount", row.settlementCount? (+row.settlementCount).toFixed(3): "");
                    }
                    this.$set(row, "mergedId", row.acceptListId);
    
                    // row.acceptTime = row.acceptTime && row.acceptTime.length > 10?row.acceptTime.substr(0, 10) : row.acceptTime;
                    // row.unitPriceWithTax1 = (+row.unitPriceWithTax).toFixed(2);
                    row.acceptCount1 = row.acceptCount ? (+row.acceptCount).toFixed(2) : "";
                    row.acceptanceCode = row.acceptCode;
                    row.manufacturerBrand = row.brand;
                    // row.moneyWithTax = (+row.moneyWithTax).toFixed(2);
                    this.$set(row, "moneyWithTax", (+row.moneyWithTax).toFixed(2));
                    this.$set(row, "unTransportCount", row.unTransportCount? (+row.unTransportCount).toFixed(3): "");
                    this.$set(row, "unitPriceWithTax", row.unitPriceWithTax? (+row.unTransportCount).toFixed(3): "");
                    row.orderCount = row.orderCount
                        ? (+row.orderCount).toFixed(3)
                        : row.orderNumber
                            ? (+row.orderNumber).toFixed(3)
                            : "";
                });
                this.$nextTick(() => {
                    this.$refs["tableList"].settlementList = result.settlementList;
                    
                });
              
            });
        }
    },
    beforeRouteLeave(to, from, next) {
        this.isTrue = false;
        this.activeName = "a";
        next();
    },
    activated() {
        this.$route.query.id?this.getDetail() : this.isTrue = true;
    }
}
</script>

<style lang="scss" scoped>
/deep/ .ccui-multifunctional-table-wrapper {
    margin-top: 40px;
}

/deep/ .el-group-title.ccui-group-wrapper .extend-btn {
    top: 0;
}

/deep/ .el-tabs__customize {
    padding-bottom: 50px;
}
</style>